Option Strict On

Imports System.Threading

Imports Sunts.HyperV.Common

Public Class HyperVBackupScheduler
    Private serviceStarted As Boolean = False
    Private bw As BackupWorker
    Private MainThread As Thread
    Private ServiceLog As String = "servicelog.log"
    Public Shared Property ConnectionString As String

    Public Enum commands
        StopRunningJob = 128
    End Enum

    Protected Overrides Sub OnStart(ByVal args As String())
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Hyper-V Backup Manager.exe.config"))
        ConnectionString = Configuration.ConfigurationManager.ConnectionStrings.Item("HyperVBackupManager.My.MySettings.ConnectionString").ConnectionString



        WriteToLogFile("Hyper-V Backup Scheduler service is starting", ServiceLog)
        serviceStarted = True
        MainThread = New Thread(New ThreadStart(AddressOf MainWorker))
        WriteToLogFile("Initialising main thread", ServiceLog)
        MainThread.Start()
    End Sub

    Protected Overrides Sub OnStop()
        serviceStarted = False
        Try
            WriteToLogFile("Hyper-V Backup Scheduler service is stopping", ServiceLog)
            If bw IsNot Nothing Then
                bw.CancelJob()
            End If
            WriteToLogFile("Hyper-V Backup Scheduler service stopped successfully", ServiceLog)
        Catch ex As Exception
            WriteToLogFile("Service stop" & ControlChars.CrLf & ex.Message & ControlChars.CrLf & ex.StackTrace, ServiceLog)
        End Try

    End Sub

    Protected Overrides Sub OnCustomCommand(command As Integer)

        MyBase.OnCustomCommand(command)
        If command = commands.StopRunningJob Then
            StopRunningJob()
        End If
    End Sub

    Private Sub MainWorker()
        Dim DatabaseCheck As DatabaseCheck

        While serviceStarted = True
            Try
                DatabaseCheck = New DatabaseCheck(HyperVBackupScheduler.ConnectionString)
                If Not DatabaseCheck.Exists Then
                    WriteToLogFile("The application will close as the database (" & DatabaseCheck.Location & ") could not be found ", ServiceLog)
                    Exit Try
                End If

                bw = New BackupWorker
                bw.Run()
                bw = Nothing

            Catch ex As Exception
                WriteToLogFile(ex.Message & ControlChars.CrLf & ex.StackTrace, ServiceLog)
            Finally
                If (serviceStarted) = True Then
                    Thread.Sleep(New TimeSpan(0, 0, 30))
                End If
            End Try
        End While
    End Sub

    Private Sub StopRunningJob()
        bw.CancelJob()
    End Sub



End Class
